03. Protecting the Resume
Protecting the Resume
Question:
Let's imagine that instead of building just for your own resume, you're building a webapp that takes in data from other users on the internet and turns it into a resume that they can use.
How might you make sure that the resume will still display correctly? Or even worse, imagine someone sets their name to equal <script src="http://hackyourwebsite.com/eviljavascript.js"></script>. Can you make sure your resume doesn't run their malicious script?
Your Challenge
For this quiz, your goal is to make sure that if a user puts HTML in their resume's JSON, it doesn't break the resume!
How? You need to make sure that the < and > from their HTML get turned into harmless strings.
When you're ready to replace all of the < and >, click "Continue to Quiz!"
Start Quiz:
var html = '<script src="http://hackyourwebsite.com/eviljavascript.js"></script>';
var charEscape = function(_html) {
var newHTML = _html;
// How will you make sure that newHTML doesn't contain any < or > ?
// Your code goes here!
// Don't delete this line!
return newHTML;
};
// Did your code work? The line below will tell you!
console.log(charEscape(html));
Solution:
Solution:
var charEscape = function(_html) {
var newHTML = _html;
newHTML = _html.replace(/</g, "<");
newHTML = newHTML.replace(/>/g, ">");
return newHTML;
};
There are a few ways to remove < and > from code. The simplest is simply replacing them with their character entity references (< and >).
To do so, we can use string.replace(old, new). Note, however, that if you pass in a string as old, string.replace(old, new) will only replace the first instance of the old string.
You must pass in a regular expression as old to replace every instance of old in the string.
In the example above, we passed /</g and />/g as old into string.replace(old, new), which are regular expressions that grab all instances of < and >.
Alternatively, you could pass an HTML string into a function like encodeURIComponent(string) to remove instances of < and >. But it isn't intended for situations like this, possibly leading to unexpected consequences.
Special thanks to Michael Händel for correcting my inaccurate solution!
INSTRUCTOR NOTE:
Follow your instructors!
@cwpittman
+jameswilliams